package cn.donting.jme.expansion.file;

import cn.donting.jme.EditorContent;
import cn.hutool.core.io.FileUtil;
import com.formdev.flatlaf.extras.FlatSVGIcon;

import javax.swing.*;
import java.io.File;
import java.net.URL;
import java.util.List;

public class FileIcon {
    public static final String iconPath = "icon/file";

    private static List<String> iconExtNames = List.of("svg", "png", "jpeg");

    public static Icon getFileIcon(File file, int size) {
        if (file.equals(EditorContent.getProject().getSrcMainDir())) {
            return new FlatSVGIcon("icon/moduleDirectory.svg",size,size);

        }
        if (file.equals(EditorContent.getProject().getSrcJavaDir())) {
            return new FlatSVGIcon("icon/sourceRoot.svg",size,size);
        }
        if (file.equals(EditorContent.getProject().getSrcResourcesDir())) {
            return new FlatSVGIcon("icon/resourcesRoot.svg",size,size);
        }

        if (file.isDirectory()) {
            if (FileUtil.isSub(EditorContent.getProject().getSrcJavaDir(), file)) {
                return new FlatSVGIcon("icon/package.svg",size,size);
            }
            return new FlatSVGIcon("icon/folder.svg",size,size);
        }
        String extName = FileUtil.extName(file);
        return getFileIcon(extName, size);
    }

    public static Icon getFileIcon(String extName, int size) {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        for (String iconExtName : iconExtNames) {
            URL resource = contextClassLoader.getResource(iconPath + "/" + extName + "." + iconExtName);
            if (resource != null) {
                switch (iconExtName) {
                    case "svg":
                        return loadSvg(resource, size);
                }
            }
        }
        return new FlatSVGIcon("icon/file/unknown.svg", size, size);
    }

    private static Icon loadSvg(URL resource, int size) {
        return new FlatSVGIcon(resource).derive(size, size);
    }

}
